package com.simpletour.qa.gateway.jwt;

import com.simpletour.qa.common.entity.Role;
import com.simpletour.qa.common.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.impl.DefaultClaims;
import org.apache.commons.lang.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 通用JWT声明
 * @author zhaohw
 * @date 2018-06-08 14:46
 * @since 1.8
 */
public class ClaimsUtil {


    public final static String CLAIM_VALUE_ISSUER = "www.simpletour.com";

    public final static String CLAIM_KEY_USER_ID = "userId";

    public final static String CLAIM_KEY_USERNAME = "username";

    public final static String CLAIM_KEY_ROLE = "role";

    /**
     * 返回一个标准Claims
     * @return
     */
    protected static Claims getCommonClaims(){
        return new DefaultClaims()
                .setId(UUID.randomUUID().toString().replace("-",""))
                .setIssuer(CLAIM_VALUE_ISSUER)
                .setIssuedAt(new Date());
    }

    /**
     * 返回带用户信息的Claims Map参数
     * @param user
     * @return
     */
    protected static Map<String,Object> getCustomClaims(User user){
        Map<String,Object> claimsMap= new HashMap<>(2);
        claimsMap.put(CLAIM_KEY_USERNAME,user.getUsername());
        claimsMap.put(CLAIM_KEY_USER_ID,user.getUserId());
        Optional<Set<Role>> role = Optional.ofNullable(user.getRoles());
        role.ifPresent(p -> {
            List<Integer> roleIdList = p.stream().map(Role::getRoleId).collect(Collectors.toList());
            claimsMap.put(CLAIM_KEY_ROLE,
                    StringUtils.join(roleIdList,","));
        });
        return claimsMap;
    }

}
